package com.jooink.sharewidget.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.Callback;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.ScriptInjector;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;

public class ShareWidgetTwitter implements IsWidget{

	private static boolean twitter_initialized=false;
	private static boolean twitter_failed=false;

	static {
		//script injection
		ScriptInjector.fromUrl("https://platform.twitter.com/widgets.js").setCallback(
				new Callback<Void, Exception>() {
					@Override
					public void onSuccess(Void result) {
						twitter_initialized=true;
						vis_twitter_element();
					}
					@Override
					public void onFailure(Exception reason) {
						twitter_failed=true;
					}
				}
				).setWindow(ScriptInjector.TOP_WINDOW).inject();		

	}
	//G-plus static list
	static List<Element> twitter_list=new ArrayList<Element>();
	static List<TwitterOptions> twitter_opts=new ArrayList<TwitterOptions>();

	//G-plus repeating command
	static void vis_twitter_element() {
		for(int i=0;i<twitter_list.size();i++) {
			twitter_render(twitter_list.get(i),twitter_opts.get(i));
		}
		twitter_list.clear();
		twitter_opts.clear();
	};


	//Plus Button
	public ShareWidgetTwitter(String href, String size, String annotation) {
		final TwitterOptions po=createOptions(href, size, annotation);
		twitter.addAttachHandler(new AttachEvent.Handler() {
			@Override
			public void onAttachOrDetach(AttachEvent event) {
				if(event.isAttached()) {
					render_twitter(po);
				}
			}
		});
	}

	private void render_twitter(TwitterOptions po) {
		if(twitter_failed)
			return;
		if(twitter_initialized) {
			twitter_render(twitter.getElement(),po);
		} else {
			twitter_list.add(twitter.getElement());
			twitter_opts.add(po);
		}
	}
	
	public static class TwitterOptions extends JavaScriptObject {
		protected TwitterOptions() {};
	}
	
	public native static TwitterOptions createOptions(String href, String size, String annotation) /*-{
		return {href:href,size:size,count:annotation};
	}-*/;

	private static native void twitter_render(Element targetEl, TwitterOptions opts) /*-{
		$wnd.twttr.widgets.createShareButton(opts.href,targetEl,function(){},opts);
	}-*/;

	private HTML twitter=new HTML();

	@Override
	public Widget asWidget() {
		return twitter;
	}
}
